﻿using DreamSpace.Net.ScriptEngines;
using DreamSpace.Net.ScriptEngines.V8;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using V8.Net;

namespace DreamSpace.Net
{
    public partial interface IServerHost<out TScriptEngine>
    {
        /// <summary>
        /// Protects the specified object for access by multiple threads and/or engine processes by putting a "mutex" lock on the object.
        /// When called, the specified call-back function is safe to access the properties and functions of the locked object.
        /// </summary>
        /// <param name="obj">The object to lock (protect) from thread access.</param>
        /// <param name="func">The function to execute within the critical section of the lock.</param>
        void Lock(object obj, Action func);

        /// <summary>
        /// Starts the specific function in a new thread.
        /// This is helpful in utilizing the CPU affinity of the host environment when a long-running task is required.
        /// </summary>
        /// <param name="name">A name to associate with this thread (cannot be the name of an ACTIVE thread).</param>
        /// <param name="userData">Arbitrary user defined data to pass to the threaded function.</param>
        /// <param name="threadedFunction">The function to execute within the new thread.</param>
        /// <param name="completedCallback">The function to call on the CALLING thread when the thread has completed.</param>
        void Run(string name, object userData, Action<object> threadedFunction, Action<object> completedCallback);

        /// <summary>
        /// Starts a server host instance.
        /// <para>The DreamSpaceServer instance contains multiple ServerHost instances that each run in a separate thread.
        /// Scripts running within any of these threads can spawn new server hosting threads as needed.</para>
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        IServerHost<TScriptEngine> Spawn(string name);
    }


    public partial class ServerHost<TScriptEngine> // This class part holds the JavaScript environment function mappings.
    {
        /// <summary>
        /// Protects the specified object for access by multiple threads and/or engine processes by putting a "mutex" lock on the object.
        /// When called, the specified call-back function is safe to access the properties and functions of the locked object.
        /// </summary>
        /// <param name="obj">The object to lock (protect) from thread access.</param>
        /// <param name="func">The function to execute within the critical section of the lock.</param>
        [ScriptMember("lock")]
        public void Lock(object obj, Action func)
        {
            lock (obj)
            {
                func();
            }
        }

        /// <summary>
        /// Starts the specific function in a new thread.
        /// This is helpful in utilizing the CPU affinity of the host environment when a long-running task is required.
        /// </summary>
        /// <param name="name">A name to associate with this thread (cannot be the name of an ACTIVE thread).</param>
        /// <param name="userData">Arbitrary user defined data to pass to the threaded function.</param>
        /// <param name="threadedFunction">The function to execute within the new thread.</param>
        /// <param name="completedCallback">The function to call on the CALLING thread when the thread has completed.</param>
        [ScriptMember("run")]
        public void Run(string name, object userData, Action<object> threadedFunction, Action<object> completedCallback)
        {
            Thread t = null;

            if (Threads == null)
                Threads = new Dictionary<string, Thread>();
            else
            {
                if (Threads.TryGetValue(name, out t) && t.IsAlive)
                    throw new InvalidOperationException("There's already an active thread named '" + name + "'.");
            }

            var callingThread = Thread.CurrentThread;
            Threads[name] = t = new Thread(() => { threadedFunction(userData); QueueMessage(MessageType.CallFunction, completedCallback, userData); });

            t.Start();
        }

        /// <summary>
        /// Starts a server host instance.
        /// <para>The DreamSpaceServer instance contains multiple ServerHost instances that each run in a separate thread.
        /// Scripts running within any of these threads can spawn new server hosting threads as needed.</para>
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [ScriptMember("spawn")]
        public IServerHost<TScriptEngine> Spawn(string name)
        {
            var sh = DreamSpaceServer.CreateServerHost<TScriptEngine>();
            sh.Start();
            return sh;
        }
    }
}
